<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>DOM的高效操作</title>
  </head>
  <body>
    <script>
      // 测试次数：一百万次
      const times = 1000000;
      // 缓存body元素
      console.time("object");
      let body = document.body;
      // 循环赋值对象作为对照参考
      for (let i = 0; i < times; i++) {
        let tmp = body;
      }
      console.timeEnd("object"); // object: 1.77197265625ms
      console.time("dom");
      // 循环读取body元素引发线程切换
      for (let i = 0; i < times; i++) {
        let tmp = document.body;
      }
      console.timeEnd("dom"); // dom: 18.302001953125ms
    </script>
  </body>
</html>
